package com.qfedu.dao.impl;

import com.qfedu.dao.UserDao;
import com.qfedu.pojo.User;
import com.qfedu.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;

/**
 * 创建者: QF-SUN
 * 创建时间: 2023/3/31 16:16
 * 描述:
 */
public class UserDaoImpl implements UserDao {
    private QueryRunner qf = new QueryRunner(DataSourceUtils.getDataSource());
    @Override
    public long selectCountByUsername(String username) {
        String sql = "select count(0) from tb_user where username = ?";
        try {
            long count = (long) qf.query(sql, new ScalarHandler(), username);
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("校验用户名失败！！！");
        }
        return 0;
    }

    //localhost:8080/userservlet?method=setState
    @Override
    public boolean insert(String username, String password, String email, String gender) {

        String sql = "INSERT INTO `tb_user`(`username`,`password`,`email`,`gender`,`flag`,`role`) VALUES(?,md5(?),?,?,1,1)";
        try {
            qf.update(sql, username, password, email, gender);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("校验用户名失败！！！");
            return false;
        }
        return true;
    }

    @Override
    public User selectByUsernameAndPwd(String username, String password, int role) {
        String sql = "select *  from tb_user where username = ? and password = md5(?) and role = ?";
        try {
            User user = qf.query(sql, new BeanHandler<>(User.class), username, password, role);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("查询用户名和密码失败！！！");
        }
        return null;
    }
}
